import store from '@/vue/store'
import { encrypt, decrypt } from './crypto'
import { ObjectCopy } from './index'
export const setLocal = (key, val) => {
  switch (typeof val) {
    case 'object':
      key += '--json'
      val = JSON.stringify(val)
      break
    case 'boolean':
      key += '--boolean'
      val = JSON.stringify(val)
      break
    case 'number':
      key += '--number'
      val = JSON.stringify(val)
      break
    default:
      key += '--def'
      val = String(val)
      break
  }
  localStorage.setItem(key, encrypt(String(val), true))
}

export const clearLocal = () => localStorage.clear()
export const removeLocal = key => localStorage.removeItem(key)

export const initStore = () => {
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i)
    const [action, type] = key.split('--')
    const val = decrypt(localStorage.getItem(key))
    switch (type) {
      case 'json':
        store.dispatch(action, JSON.parse(val))
        break
      case 'boolean':
        store.dispatch(action, val === 'true')
        break
      case 'number':
        store.dispatch(action, parseInt(val) || 0)
        break
      case 'def':
        store.dispatch(action, val)
        break
      default:
        console.warn(key, ', this key is not a canonical storage information')
        break
    }
  }
}
const handleMenus = (arr, val, i) => {
  if (i) arr.push(ObjectCopy(val))
  return arr
}

export const setLocalMenus = data => {
  setLocal('menu/setActiveMenus', data.reduce(handleMenus, []))
}
